package com.example.physicalexaminationsystem.controller;

import cn.hutool.core.collection.CollUtil;
import com.example.physicalexaminationsystem.dto.ResponseDto;
import com.example.physicalexaminationsystem.mapper.UserDao;
import com.example.physicalexaminationsystem.model.UserEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shiwenzhuo
 * 
 * @description
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private UserDao userDao;

    @RequestMapping("/login")
    public ResponseDto login(@RequestBody Map<String, Object> params) {
        String name = params.get("name").toString();
        String passport = params.get("passport").toString();
        String password = params.get("password").toString();
        Map<String, Object> user = new HashMap<>();
        user.put("name", name);
        user.put("passport", passport);
        List<UserEntity> userEntities = userDao.selectByMap(user);
        if (CollUtil.isEmpty(userEntities)) {
            return ResponseDto.fail("用户不存在");
        }
        if (!userEntities.get(0).getPassword().equals(password)) {
            return ResponseDto.fail("密码错误");
        }
        return ResponseDto.success();
    }

    @RequestMapping("/register")
    public ResponseDto register(@RequestBody Map<String, Object> params) {
        String name = params.get("name").toString();
        String passport = params.get("passport").toString();
        String password = params.get("password").toString();
        Map<String, Object> user = new HashMap<>();
        user.put("name", name);
        user.put("passport", passport);
        List<UserEntity> userEntities = userDao.selectByMap(user);
        if (!CollUtil.isEmpty(userEntities)) {
            return ResponseDto.fail("用户已存在");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setName(name);
        userEntity.setPassport(passport);
        userEntity.setPassword(password);
        userEntity.setCreateTime(new Date());
        userDao.insert(userEntity);
        return ResponseDto.success();
    }
}
